# -*- coding:utf-8 -*-
'''
author:***y
time:2019-10-10
主要功能说明：
1、获取登录接口的token
2、运动记录中运动种类识别

'''
import requests
import csv
import json
import time

class Test_sport_parse():

    def __init__(self):
        print("-------------测试开始----------------")

    def login_token(self):
        # 初始化登录接口
        login_url = 'https://api.icarbonx.com/oauth2/token?grant_type=password&sms_verify=true'
        login_header = {"Authorization": "Basic Y29tLm1ldW0uY29hY2guaXBob25lOjdmYTYyZmFmYzgxZTgwMzY="}
        login_data = {
            "username": "15112345678",
            "password": "888888",
            "appName": "health-buddy",
            "grant_type": "password",
            "sms_verify": "true"
        }
        # 登录请求接口
        r_login = requests.post(url=login_url,data=login_data,headers=login_header)
        # 获取登录的响应报文
        token = r_login.json()['access_token']
        # print(token)
        '''请求接口获取token值'''
        return token

    def sport_parse(self):
        # 初始化
        sport_flag_init = 0
        sport_error_init = 0
        # 开始时间
        start = time.time()

        #读取csv文件，获取msg的入参
        with open('E:\\test\\HB\\sport_parse_init_1.csv','r') as sp:
            reader = csv.reader(sp)
            #从文本第二行开始读取
            next(reader)
            for row in reader:
                print(row[0])
                #疾病食材问答接口的请求参数msg
                sp_msg = {"msg":row[0],"types":"sport","weight":50}
                print(sp_msg)
                # 获取登录的token
                sp_headers = {"Authorization": "Bearer " + self.login_token()}

                #运动种类识别url
                sp_url = 'https://api.icarbonx.com/ai/nlp/v1.0/sport-parse-unit'
                #运动种类识别请求接口
                r_sp = requests.post(url=sp_url,headers= sp_headers,data=sp_msg)
                #获取运动种类识别的响应报文
                print(r_sp)
                sp_response = json.loads(r_sp.text)
                print(sp_response)
                print(type(sp_response))

                #判断响应结果是否为空，不空则获取properties.sub_properties.sport_cals的值
                if sp_response:
                    print(sp_response)
                    sport_flag_init = sport_flag_init + 1
                    print("动作推荐成功%d"%sport_flag_init)
                    #获取响应结果中的sport_cals、mileage、steps
                    sport_response_all = sp_response[0]

                    sport_code = sport_response_all['properties']['code']
                    sport_cals = sport_response_all['properties']['sub_properties']['sport_cals']
                    sport_steps = sport_response_all['properties']['sub_properties']['steps']
                    sport_mileage = sport_response_all['properties']['sub_properties']['mileage']
                    # print(sport_cals)
                    # print(sport_steps)
                    # print(sport_mileage)
                    # print(type(sport_cals))
                    # print(type(sport_steps))
                    # print(type(sport_mileage))
                    #将int转换为str
                    sport_code = str(sport_code)
                    sport_cals = str(sport_cals)
                    sport_steps = str(sport_steps)
                    sport_mileage = str(sport_mileage)
                    # print(type(action_recommend_code))



                    sport_parse = ['sp_msg','sp_cals','sp_steps','sp_mileage','sport_code']

                    #保存响应结果到本地文件
                    with open('E:\\test\\HB\\sport_parse_success.csv', 'a+', encoding='utf-8-sig') as dof:
                        sport_parse[0] = row[0]
                        #将返回结果中的删除，避免换行
                        print(sport_response_all)
                        # if '\n' in action_response_all:
                        #     action_response_all = action_response_all.replace("\n","")

                        sport_parse[1] = sport_cals
                        sport_parse[2] = sport_steps
                        sport_parse[3] = sport_mileage
                        sport_parse[4] = sport_code
                        dof.write(','.join(sport_parse))
                        dof.write('\n')
                        dof.close()

                else:
                    sport_error_init = sport_error_init + 1
                    print("动作推荐结果为空，可能未识别到动作名称%d"%sport_error_init)
                    with open('E:\\test\\HB\\sport_parse_fail.csv', 'a+', encoding='utf-8-sig') as doff:
                        sport_parse_fail = ['sp_msg']
                        sport_parse_fail[0] = row[0]
                        doff.write(','.join(sport_parse_fail))
                        doff.write('\n')
                        doff.close()
        sp.close()


        print("------运动识别结果统计"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+"------")
        print("运动识别成功%d" % sport_flag_init)
        print("运动识别无结果%d" % sport_error_init)
        # 计算花费的时间
        print('cost time:{}'.format(time.time() - start))



if __name__ == '__main__':
    dac = Test_sport_parse()
    dac.sport_parse()










